package lzk.myshop.service.impl;

import lzk.myshop.dao.*;
import lzk.myshop.Util.GoodsAdd;
import lzk.myshop.Util.Goodss;
import lzk.myshop.Util.OrderToUser;
import lzk.myshop.Util.UserAll;
import lzk.myshop.pojo.*;
import lzk.myshop.service.UsersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

@Transactional
@Service
public class UsersServiceImpl implements UsersService {
    @Autowired
    UsersMapper usersMapper;
    @Autowired
    CartMapper cartMapper;
    @Autowired
    GoodsMapper goodsMapper;
    @Autowired
    CartDetailMapper cartDetailMapper;
    @Autowired
    OrderMapper orderMapper;
    @Autowired
    OrderDetailMapper orderDetailMapper;
    @Autowired
    MerchantMapper merchantMapper;

    @Override
    /**
     * 用户登录,使用手机号/邮箱+密码的方式登录
     * */
    public Map<String,Object> signin(String account, String password){
        Map<String,Object> result = new HashMap<>();
        UserAll userAll;
        Users users;
        if (account.contains("@")){
            users = usersMapper.selectbyemail(account,password);
        }else {
            users = usersMapper.selectbyphone(account,password);
        }
        if (users!=null){
            userAll = new  UserAll(users,cartMapper.selectbyuserid(users.getId()));
            result.put("code",1);
            result.put("massage","登陆成功");
            result.put("data",userAll);
        }else {
            result.put("code",0);
            result.put("massage","登陆失败，账号或密码错误");
            result.put("data",null);
        }
        return result;
    }


    @Override
    /**
     * 用户注册
     * */
    public Map<String,Object> addUser(Users users){
        Map<String,Object> result = new HashMap<>();
        String r = usersMapper.ifExist(users.getEmail(),users.getPhone());
        if (r.equals("存在")){
            result.put("code",0);
            result.put("massage","邮箱或手机号已经存在");
            result.put("data",null);
        }else {
            int b = usersMapper.save(users);
            if (b == 0){
                result.put("code",-1);
                result.put("massage","注册失败");
                result.put("data",null);
            }else {
                int i = cartMapper.save(usersMapper.getId(users.getPhone(), users.getPassword()));
                if (i == 0){
                    result.put("code",-2);
                    result.put("massage","注册失败");
                    result.put("data",null);
                }
                else {
                    result.put("code",1);
                    result.put("massage","注册成功");
                    result.put("data",null);
                }
            }
        }
        return result;
    }


    @Override
    /**
     * 返回所有商品
     * */
    public Map<String, Object> allGoods() {
        List<Goods> g = goodsMapper.allGoods();
        Map<String,Object> result = new HashMap<>();
        result.put("code",1);
        result.put("massage","查询到"+g.size()+"条数据");
        result.put("data",g);
        return result;
    }


    @Override
    /**
     * 查询商品
     * */
    public Map<String, Object> searchGoods(String name) {
        List<Goods> g = goodsMapper.searchGoodsByName(name);
        Map<String,Object> result = new HashMap<>();
        result.put("code",1);
        result.put("massage","查询到"+g.size()+"条数据");
        result.put("data",g);
        return result;
    }


    @Override
    /**
     * 添加商品到购物车
     * */
    public Map<String,Object> addCart(int cartid,int goodsID,int count){
        CartDetail cartDetail = new CartDetail();
        cartDetail.setCartid(cartid);
        cartDetail.setGoodsid(goodsID);
        cartDetail.setNumber(count);
        cartDetail.setGoodsname(goodsMapper.getGoodsNameByID(goodsID));
        cartDetail.setPrice(goodsMapper.getPrice(goodsID));
        int i = cartDetailMapper.addCart(cartDetail);
        Map<String,Object> result = new HashMap<>();
        if (i==1){
            result.put("code",1);
            result.put("massage","添加成功");
            result.put("data",null);
        }else {
            result.put("code",0);
            result.put("massage","添加失败");
            result.put("data",null);
        }
        return result;
    }


    @Override
    /**
     * 用户修改手机号
     * */
    public Map<String, Object> alterPhone(String newPhone, int userid) {
        Map<String,Object> result = new HashMap<>();
        if (usersMapper.ifPhoneExist(newPhone).equals("不存在")){
            int i=usersMapper.alterPhone(newPhone,userid);
            if (i==1){
                result.put("code",1);
                result.put("massage","修改成功");
                result.put("data",null);
            }else{
                result.put("code",-1);
                result.put("massage","修改失败");
                result.put("data",null);
            }
        }else {
            result.put("code",-2);
            result.put("massage","该手机号已存在");
            result.put("data",null);
        }
        return result;
    }


    @Override
    /**
     * 用户修改邮箱
     * */
    public Map<String, Object> alterEmail(String newEmail, int userid) {
        Map<String,Object> result = new HashMap<>();
        if (usersMapper.ifPhoneExist(newEmail).equals("不存在")){
            int i=usersMapper.alterEmail(newEmail,userid);
            if (i==1){
                result.put("code",1);
                result.put("massage","修改成功");
                result.put("data",null);
            }else{
                result.put("code",-1);
                result.put("massage","修改失败");
                result.put("data",null);
            }
        }else {
            result.put("code",-2);
            result.put("massage","该邮箱已存在");
            result.put("data",null);
        }
        return result;
    }


    @Override
    /**
     * 用户修改地址
     * */
    public Map<String, Object> alterAddress(String newAddress, int userid) {
        Map<String,Object> result = new HashMap<>();
        int i=usersMapper.alterAddress(newAddress,userid);
        if (i==1){
            result.put("code",1);
            result.put("massage","修改成功");
            result.put("data",null);
        }else{
            result.put("code",-1);
            result.put("massage","修改失败");
            result.put("data",null);
        }
        return result;
    }

    @Override
    public Map<String, Object> getAllOrder(int userid) {
        Map<String,Object> result = new HashMap<>();
        List<Order> L = orderMapper.getOrderByUserId(userid);
        if (L.size()==0){
            result.put("code",0);
            result.put("massage","没有订单信息");
            result.put("data",null);
            return result;
        }
        List<OrderToUser> LR = new ArrayList<>();
        for (int i=0;i<L.size();i++){
            List<OrderDetail> orderDetails = orderDetailMapper.getOrderDByOrderId(L.get(i).getId());
            for (int j=0;j<orderDetails.size();j++){
                OrderToUser order = new OrderToUser(L.get(i),orderDetails.get(j));
                LR.add(order);
            }
        }
        result.put("code",1);
        result.put("massage","查询到"+L.size()+"条数据");
        result.put("data",LR);
        return result;
    }


    @Override
    public Map<String, Object> newOrder(GoodsAdd goodsAdds) {
        // 创建一个DateTimeFormatter对象，用于格式化日期和时间
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        // 获取当前日期和时间
        LocalDateTime currentDateTime = LocalDateTime.now();
        // 使用DateTimeFormatter将日期和时间格式化为字符串
        String formattedDateTime = currentDateTime.format(formatter);

        double tp = 0;
        int n = goodsAdds.getGoodsL().size();
        Map<String,Object> result = new HashMap<>();

        if (n == 0){
            result.put("code",-1);
            result.put("message","没有商品");
            result.put("data",null);
            return result;
        }
        for (int i=0;i<n;i++) {
            Goodss goodss = goodsAdds.getGoodsL().get(i);
            Goods g = goodsMapper.getGoodsByid(goodss.getGoodsid());
            tp+=g.getPrice()*goodss.getCount();
        }
        Order order = new Order();
        order.setUserid(goodsAdds.getUserid());
        order.setTotalprice(tp);
        order.setStarttime(formattedDateTime);
        order.setOvertime(null);
        order.setStatus(0);
        order.setReceiver(goodsAdds.getReceiver());
        order.setPhone(goodsAdds.getPhone());
        order.setArrivaladdress(goodsAdds.getAddress());
        order.setRemark(goodsAdds.getRemark());

        int ri = orderMapper.newOrder(order);
        int id = order.getId();
        List<OrderDetail> orderDetails=new ArrayList<>();

        for (int i=0;i<n;i++){
            Goodss goodss= goodsAdds.getGoodsL().get(i);
            Goods g = goodsMapper.getGoodsByid(goodss.getGoodsid());
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setOrderid(id);
            orderDetail.setGoodsid(g.getId());
            orderDetail.setGoodsname(g.getName());
            orderDetail.setPrice(g.getPrice());
            orderDetail.setNumber(goodss.getCount());
            orderDetail.setTotalprice(g.getPrice()*goodss.getCount());
            orderDetail.setMerchantid(goodsMapper.getMerIDByGoodsID(goodss.getGoodsid()));
            orderDetail.setMerchantname(merchantMapper.getMerNameByid(goodsMapper.getMerIDByGoodsID(g.getId())));
            orderDetail.setSentaddress(merchantMapper.getAddress(goodsMapper.getMerIDByGoodsID(g.getId())));
            orderDetails.add(orderDetail);
        }

        orderDetailMapper.newOrder(orderDetails);
        result.put("code",1);
        result.put("message","生成成功，返回orderid");
        result.put("data",id);
        return result;
    }



    @Override
    public Map<String, Object> newOrderByCartId(int cartid){
        Map<String,Object> result = new HashMap<>();
        int userid = cartMapper.getUserIDByID(cartid);
        List<CartDetail> cartDetails = cartDetailMapper.getAllCart(cartid);
        Users users = usersMapper.getUserByID(userid);
        if (cartDetails.size()==0){
            result.put("code",-1);
            result.put("message","购物车中没有商品");
            result.put("data",null);
            return result;
        }
        double tp = 0;
        for (int i=0;i<cartDetails.size();i++){
            Goods goods = goodsMapper.getGoodsByid(cartDetails.get(i).getGoodsid());
            tp+= goods.getPrice()*cartDetails.get(i).getNumber();
        }

        // 创建一个DateTimeFormatter对象，用于格式化日期和时间
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        // 获取当前日期和时间
        LocalDateTime currentDateTime = LocalDateTime.now();
        // 使用DateTimeFormatter将日期和时间格式化为字符串
        String formattedDateTime = currentDateTime.format(formatter);

        Order order = new Order();
        order.setUserid(userid);
        order.setTotalprice(tp);
        order.setStarttime(formattedDateTime);
        order.setReceiver(users.getName());
        order.setPhone(users.getPhone());
        order.setArrivaladdress(users.getAddress());
        order.setRemark("null");
        order.setStatus(0);

        int ri = orderMapper.newOrder(order);
        int id = order.getId();
        List<OrderDetail> orderDetails=new ArrayList<>();
        for (int i=0;i<cartDetails.size();i++){
            Goods g = goodsMapper.getGoodsByid(cartDetails.get(i).getGoodsid());
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setOrderid(id);
            orderDetail.setGoodsid(g.getId());
            orderDetail.setGoodsname(g.getName());
            orderDetail.setPrice(g.getPrice());
            orderDetail.setNumber(cartDetails.get(i).getNumber());
            orderDetail.setTotalprice(g.getPrice()*cartDetails.get(i).getNumber());
            orderDetail.setMerchantid(goodsMapper.getMerIDByGoodsID(cartDetails.get(i).getGoodsid()));
            orderDetail.setMerchantname(merchantMapper.getMerNameByid(goodsMapper.getMerIDByGoodsID(g.getId())));
            orderDetail.setSentaddress(merchantMapper.getAddress(goodsMapper.getMerIDByGoodsID(g.getId())));
            orderDetails.add(orderDetail);
        }
        orderDetailMapper.newOrder(orderDetails);
        result.put("code",1);
        result.put("message","生成成功，返回orderid");
        result.put("data",id);

        for (int i=0;i<cartDetails.size();i++){
            cartMapper.deleteCartDetail(cartDetails.get(i).getId());
        }
        return result;
    }



    @Override
    public Map<String, Object> deleteOrder(int id) {
        int i = orderMapper.deleteOrder(id);
        Map<String,Object> result = new HashMap<>();
        if (i==1){
            result.put("code",1);
            result.put("massage","取消成功");
            result.put("data",null);
        }else{
            result.put("code",-1);
            result.put("massage","该订单不能被取消");
            result.put("data",null);
        }
        return result;
    }

    @Override
    public Map<String, Object> getGoods(int id) {
        int i = orderMapper.getGoods(id);
        Map<String,Object> result = new HashMap<>();
        if (i==1){
            result.put("code",1);
            result.put("massage","收货成功");
            result.put("data",null);
        }else{
            result.put("code",-1);
            result.put("massage","收货失败");
            result.put("data",null);
        }
        return result;
    }

    @Override
    public Map<String, Object> deleteUser(int userid) {
        int i = usersMapper.ifCanDelete(userid);
        Map<String,Object> result = new HashMap<>();
        if (i != 0){
            result.put("code",-1);
            result.put("message","您有订单仍未完成，暂时不能消除账户");
            result.put("data",null);
        }else{
            usersMapper.deleteUser(userid);
            result.put("code",0);
            result.put("message","销户成功");
            result.put("data",null);
        }
        return result;
    }


    @Override
    public Map<String, Object> getCart(int cartid) {
        List<CartDetail> cartDetails = cartDetailMapper.getAllCart(cartid);
        Map<String,Object> result = new HashMap<>();
        result.put("code",1);
        result.put("message","查询到"+cartDetails.size()+"条数据");
        result.put("data",cartDetails);
        return result;
    }

    @Override
    public Map<String, Object> deleteCart(int cartDetailid){
        int i = cartDetailMapper.deleteCart(cartDetailid);
        Map<String,Object> result = new HashMap<>();
        if (i==1){
            result.put("code",1);
            result.put("message","删除成功");
            result.put("data",null);
        }else {
            result.put("code",-1);
            result.put("message","删除失败");
            result.put("data",null);
        }
        return result;
    }
}
